package com.mtons.mblog.base.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.dozer.DozerBeanMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * 通过json序列化及反系列化copy属性信息
 */
public class BeanUtils {

    private static final DozerBeanMapper mapper = new DozerBeanMapper();

//    public static <T> T copyProperties(Object source, Class<T> clazz) {
//
//        if(source == null) {
//            throw new RuntimeException("source object is null!");
//        }
//
//        //SerializerFeature.DisableCircularReferenceDetect 解决循环引用的问题
//        String jsonStr = JSON.toJSONString(source, SerializerFeature.DisableCircularReferenceDetect);
//        return JSON.parseObject(jsonStr, clazz);
//    }


    public static <T> T copyProperties(Object source, TypeReference<T> type) {

        if(source == null) {
            throw new RuntimeException("source object is null!");
        }

        String jsonStr = JSONObject.toJSONString(source, SerializerFeature.DisableCircularReferenceDetect);
        return JSONObject.parseObject(jsonStr, type);
    }


    public static <S, T> List<T> copyProperties(List<S> origLst, Class<T> destClz) {
        List<T> destLst = new ArrayList<>();
        if(origLst == null || origLst.isEmpty()) return destLst;

        for(S orig : origLst) {
            T dest = copyProperties(orig, destClz);
            destLst.add(dest);
        }
        return destLst;
    }

    public static <S, T> T copyProperties(S orig, T dest)  {
        if(orig == null) return null;

        mapper.map(orig, dest);
        return dest;
    }

    public static <S, T> T copyProperties(S orig, Class<T> destClz) {
        if(orig == null) return null;

        return mapper.map(orig, destClz);
    }

}
